/**
 * 
 */
package src.gui;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import sql.QueryPackage;
/**
 * @author Administrator
 *
 */
public class CodeBehind {
	public static Form f;
	public static ConnectForm connectForm;
	public static Socket s;
	public static ObjectOutputStream oos;
	public static ObjectInputStream ois;
	public static String userName;
	public static String pass;
	public static void Connect(){
		if (connectForm == null) {
			connectForm = new ConnectForm("Connect");									
		}
		f.setEnabled(false);
		connectForm.reset();
		connectForm.autoFocus();
		connectForm.setVisible(true);
			
	}
	public static void inputEvent(boolean isAccept, String userName, String pass, String ip) {
		if (isAccept) {
			ConnectToServer(ip, userName, pass);
			connectForm.setVisible(false);
			f.setEnabled(true);
		}
		else
		{
			connectForm.setVisible(false);			
			f.setEnabled(true);
		}
	}
	private static void ConnectToServer(String ip, String user, String pas) {
		try{
			s = new Socket(ip, 18119);			
			userName = user;
			pass = pas;
			OutputStream os = s.getOutputStream();			
			oos = new ObjectOutputStream(os);			
			QueryPackage qk = new QueryPackage(null, userName, pass, InetAddress.getLocalHost().toString(), null);
			oos.writeObject(qk);			
			InputStream is = s.getInputStream();
			ois = new ObjectInputStream(is);
			qk = (QueryPackage)ois.readObject();
			if (qk == null)
				throw new Exception("Can't receive data, try connect again");
			List<String> databases = (List<String>) qk.data;
			f.jComboBox1.removeAll();			
			f.jComboBox1.setModel(new DefaultComboBoxModel<>(databases.toArray()));
			f.jComboBox1.revalidate();
			f.jMenuItem2.setEnabled(true);
			f.jMenuItem1.setEnabled(false);
		}
		catch (Exception e) {
			JOptionPane.showMessageDialog(f, e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
		}
		 
	}
	public static void executeQuery() {
		if (f.jTextArea1.getSelectedText() == null){
			JOptionPane.showMessageDialog(f, "Ban Phai Chon Vung Lenh Duoc Thuc Thi Truoc", "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}
		if (s == null) {
			JOptionPane.showMessageDialog(f, "Hay Ket Noi Den Server Truoc", "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}
		List<String> queries = src.client.Query.getQuery(f.jTextArea1.getSelectedText());
		f.jTabbedPane1.removeAll();
		for (int i = 0; i < queries.size(); i++) {
			String query = queries.get(i);
			try {										
				QueryPackage qk = new QueryPackage(query, userName, pass, InetAddress.getLocalHost().toString(), f.jComboBox1.getModel().getSelectedItem().toString());			
				qk.data = f.jComboBox1.getModel().getSelectedItem().toString();
				oos.writeObject(qk);						
				qk = (QueryPackage)ois.readObject();
				if (qk == null)
					throw new Exception("Can't receive data, try connect again");
				List<List<String>> resultSet = (List<List<String>>) qk.data;
				List<String> header = resultSet.get(0);
				TableModel model = new TableModel();
				JTable table = new JTable(model);
				for (int j = 0; j < header.size(); j++) {
					model.getM_columns().add(new ColumnData(header.get(j), 200, JLabel.CENTER));	
				}			
				for (int j = 0; j < header.size(); j++) {
		            DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
		            renderer.setHorizontalAlignment(JLabel.CENTER);
		            TableColumn column = new TableColumn(j, 200, renderer, null);
		            column.setIdentifier(header.get(j));
		            table.addColumn(column);
		        }					
				for (int j = 1; j < resultSet.size(); j++) {
					List<String> data = resultSet.get(j);
					Vector<String>row = new Vector<String>();
					for (int k = 0; k < data.size(); k++) {
						row.add(data.get(k));
					}
					model.addRow(row);
				}											
				JScrollPane scroll = new JScrollPane(table);				
				f.jTabbedPane1.add(scroll);
				
			}
			catch (Exception e) {
				if (query.toLowerCase().indexOf("select") >= 0)
					JOptionPane.showMessageDialog(f, e.toString(), "Error", JOptionPane.ERROR_MESSAGE);			
			}
			f.jTabbedPane1.revalidate();
		}
	}	
	
	public static boolean exit() {
		if (s != null) {
			try {
				s.close();
				s = null;
				f.jMenuItem2.setEnabled(false);
				f.jMenuItem1.setEnabled(true);
			}
			catch (Exception e) {
				return false;
			}
		}
		return true;
	}
	public static void disconect() {
		exit();
	}
	
}
